package com.tanhua.api.impl.mongo;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.api.mongo.PublishApi;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;



@Service
public class PublishApiImpl implements PublishApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    public String save(Publish publish) {

        // 1 设置一下publish的那个pid(给大数据--要求这个字段必须是数字且唯一 工具类去设置)
        Long pid = idService.getNextId("quanzi_publish"); //指定返回一个自增的且是数字的唯一值
        publish.setPid(pid);

        // 2 保存文字和图片到动态发布表
        publish.setId(new ObjectId());
        mongoTemplate.insert(publish);
        // 3 保存数据到个人动态表
        Album album = new Album();
        album.setCreated(publish.getCreated());
        album.setPublishId(publish.getId());
        mongoTemplate.insert(album,"quanzi_album_"+publish.getUserId());
        // 4 查询自己的好友
        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //5 保存数据到好友的时间线表中
        if(CollectionUtil.isNotEmpty(friendList)){
            for (Friend friend : friendList) {
                 //有一个好友就得有一个实现线
                TimeLine timeLine = new TimeLine();
                timeLine.setUserId(publish.getUserId());
                timeLine.setCreated(publish.getCreated());
                timeLine.setPublishId(publish.getId());
                mongoTemplate.insert(timeLine,"quanzi_time_line_"+friend.getFriendId());
            }
        }

        return publish.getId().toString();
    }

    @Override
    public PageBeanVo findMyPublish(Integer page, Integer pagesize, long userId) {

        // 查询个人表
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Album> albumList = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);

        // 查询动态表
        List<Publish> publishList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(albumList)){
            for (Album album : albumList) {
                Publish publish = mongoTemplate.findById(album.getPublishId(), Publish.class);
                publishList.add(publish);
            }
        }

        Query query1 = new Query(Criteria.where("state").is(1).and("userId").is(userId));
        long count = mongoTemplate.count(query1, "quanzi_publish");


        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,count,publishList);
        return pageBeanVo;
    }

    @Override
    public PageBeanVo findFriendsInfo(Integer page, Integer pagesize, Long userId) {
        // 查询个人表
        Query query = new Query();
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<TimeLine> timelineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);

        // 查询动态表
        List<Publish> publishList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(timelineList)){
            for (TimeLine timeLine : timelineList) {
                Publish publish = mongoTemplate.findById(timeLine.getPublishId(), Publish.class);
                publishList.add(publish);
            }
        }

        Integer size = publishList.size();
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,size.longValue(),publishList);
        return pageBeanVo;
    }

    @Override
    public PageBeanVo findRecommendInfo(Integer page, Integer pagesize, Long userId) {
        // 查询推荐表 根据自己的用户id查询给自己推荐的信息
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<RecommendQuanzi> recommendQuanziList = mongoTemplate.find(query, RecommendQuanzi.class, "recommend_quanzi");

        // 查询动态表
        List<Publish> publishList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(recommendQuanziList)){
            for (RecommendQuanzi recommendQuanzi : recommendQuanziList) {
                Publish publish = mongoTemplate.findById(recommendQuanzi.getPublishId(), Publish.class);
                publishList.add(publish);
            }
        }

        Integer size = publishList.size();
        PageBeanVo pageBeanVo = new PageBeanVo(page,pagesize,size.longValue(),publishList);
        return pageBeanVo;
    }

    @Override
    public Publish findById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId),Publish.class);
    }

    @Override
    public PageBeanVo messages(Integer page, Integer pagesize, Long uid, Integer state) {

        //核心：要根据不同的业务 查询出来不同的数据
                    // 用户的动态
                    // 动态审核的动态
                        //Query query = new Query(Criteria.where("userId").is(uid).and("state").is(state));

        Query query = new Query();
        Criteria criteria = new Criteria();
        if(uid!=null){
            criteria.and("userId").is(uid);
        }
        if(state!=null){
            criteria.and("state").is(state);
        }
        query.addCriteria(criteria);


        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        long count = mongoTemplate.count(query, Publish.class);

        return new PageBeanVo(page,pagesize,count,publishList);
    }

    @Override
    public void updateState(String publishId, Integer state) {

        Query query = new Query(Criteria.where("id").is(new ObjectId(publishId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.upsert(query,update,Publish.class);
    }

    @Override
    public Publish findPid(long pid) {
        Query query = new Query(Criteria.where("pid").is(pid));
        return mongoTemplate.findOne(query,Publish.class);
    }
}
